package com.team_project.boot.controller;

import com.team_project.boot.entity.Index;
import com.team_project.boot.entity.Manager;
import com.team_project.boot.entity.User;
import com.team_project.boot.mapper.IndexMapper;
import org.apache.ibatis.annotations.Insert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class IndexController {
    @Autowired(required = false)
    IndexMapper mapper;
    @RequestMapping("/selectlist")
        public List<Index> selectAll(){
            return mapper.selectAll();
        }
    @RequestMapping("/addDesign")
    public int addDesign(Index index, HttpSession session, MultipartFile file){
        System.out.println("index = " + index + ", session = " + session + ", file = " + file);
            Manager user = (Manager) session.getAttribute("userM");
            if (user==null){
                return 2;
            }
            String fileName = file.getOriginalFilename();
            String suixx = fileName.substring(fileName.lastIndexOf("."));
            fileName = UUID.randomUUID() + suixx;
        //日期相关的路径
        SimpleDateFormat f = new SimpleDateFormat("/yyyy/MM/dd/");
        /*创建表示当前时间的日期对象*/
        Date date = new Date();
        //得到日期路径
        String datePath = f.format(date);
        String path = "E:/upload"+datePath;
        File dir = new File(datePath+fileName);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(path+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String url = datePath+fileName;
        index.setUrl(url);
        mapper.insert(index);
        return 1;
    }
    @RequestMapping("/currentManager")
    public int current(HttpSession session){
        Manager m = (Manager) session.getAttribute("userM");
        return m!=null?1:2;
    }

    @RequestMapping("/selectBanner")
    public List<Index> selectBanner(){
        return mapper.selectBanner();
    }
}
